package com.cd2cd.code_app.log;

import com.cd2cd.code_app.util.FileUtil;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;

import java.io.File;
import java.io.RandomAccessFile;

@Slf4j
public class LogFile {

    private static RandomAccessFile logFile;

    // 将 char[] 强转为 byte[]
    public static byte[] getBytes(char[] chars) {
        byte[] result = new byte[chars.length];
        for (int i = 0; i < chars.length; i++) {
            result[i] = (byte) chars[i];
        }
        return result;
    }

    @SneakyThrows
    public static String getNewLogStr() {
        if (logFile == null) {

            String runPath = FileUtil.getRunPath();
            if (runPath.contains("target/classes/")) {
                // test
                runPath = runPath.replace("target/classes/", "") + "..";

            } else {
                // dist
            }
            runPath = runPath + FileUtil.FOLDER_PATH + "/logs/default.log";

            log.info("runPath:" + runPath);
            if (new File(runPath).exists()) {
                logFile = new RandomAccessFile(runPath, "r");
                logFile.seek(logFile.length() + 1);
            }
        }

        if (logFile == null) {
            return null;
        }

        String content = logFile.readLine();
        if (StringUtils.isBlank(content))
            return null;

        byte[] bytes = getBytes(content.toCharArray());
        return new String(bytes);
    }


    @SneakyThrows
    public static void main(String[] args) {

        while (true) {
            String line = getNewLogStr();
            if (StringUtils.isNotBlank(line))
                log.info(line);
            Thread.sleep(1000);
        }
    }
}
